package com.wbs.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wbs.mapper.TbBrandMapper;
import com.wbs.model.TbBrand;
import com.wbs.model.TbBrandExample;
import com.wbs.resutil.PageBean;
import com.wbs.resutil.PageResult;
import com.wbs.service.BrandService;
import com.wbs.vo.BrandVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 芝梦
 * @Description:
 * @DateTime: 2024/1/23 15:02
 */
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private TbBrandMapper tbBrandMapper;

    /**
     * 获取所有BrandVO集合
     * 使用 stream 流 和 Lambda 表达式
     * BeanUtils.copyProperties(x, brandVO); 方法可以将前面的实体类中相同属性copy给后面的实体类
     * @return
     */
    @Override
    public List<BrandVO> findBrandAll() {
        List<TbBrand> tbBrandList = tbBrandMapper.selectByExample(null);
        //List<TbBrand> -> List<BrandVO>
        List<BrandVO> brandVOList = tbBrandList.stream().map((x) -> {
            BrandVO brandVO = new BrandVO();
            BeanUtils.copyProperties(x, brandVO);
            return brandVO;
        }).collect(Collectors.toList());
        return brandVOList;
    }

    //模糊分页查询
    @Override
    public PageResult<BrandVO> findBrandPage(PageBean<BrandVO> pageBean) {
        TbBrandExample brandExample = new TbBrandExample();
        //模糊查询条件    name品牌名称不为空时
        if (!StrUtil.isEmpty(pageBean.getBean().getName())){
            brandExample.createCriteria().andNameLike("%"+pageBean.getBean().getName()+"%");
        }
        //模糊查询条件    firstChar品牌首字符不为空时
        if (!StrUtil.isEmpty(pageBean.getBean().getFirstChar())){
            brandExample.createCriteria().andFirstCharLike("%"+pageBean.getBean().getFirstChar()+"%");
        }
        //开启分页
        PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<TbBrand> tbBrands = tbBrandMapper.selectByExample(brandExample);
        PageInfo<TbBrand> pageInfo = new PageInfo<>(tbBrands);

        //转换
        List<BrandVO> brandVOList = pageInfo.getList().stream().map((x) -> {
            BrandVO brandVO = new BrandVO();
            BeanUtils.copyProperties(x, brandVO);
            return brandVO;
        }).collect(Collectors.toList());

        return new PageResult<>(pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getTotal(),brandVOList);
    }
}
